<?php

namespace MLM\Controller;

use Zend\View\Model\ViewModel;
use Zend\Authentication\Result;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Adapter\DbTable as AuthAdapter;

class AdminController extends \MLM\Model\Generic\Controller {

    public function indexAction() {
        $identity = $this->hasSession();
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $this->layout()->navMenu = "<li class='active'>Dashboard</li>";

        return new ViewModel();
    }

    public function profileAction() {
        $identity = $this->hasSession();

        $storage = new \MLM\Model\Member\Storage($this->_db);
        $storageContact = new \MLM\Model\Member\Contact\Storage($this->_db);
        $storageAcc = new \MLM\Model\Member\Account\Storage($this->_db);


        $memberId = $identity->member_id;

        $profile = $storage->getMemberDetail($memberId);
        $contact = $storageContact->getMemberContact($memberId);
        $banks = $storageAcc->getAccountBank($memberId);

        $dataBank = array();
        while ($banks->next()) {
                $bank = $banks->current();
                $dataBank['account_id'] = $bank['account_id'];
                $dataBank['account_num'] = $bank['account_num'];
                $dataBank['account_name'] = $bank['account_name'];
                $dataBank['account_status'] = $bank['account_status'];
                $dataBank['bank_id'] = $bank['bank_id'];
                $dataBank['bank_name'] = $bank['bank_name'];
                $dataBank['bank_acc_no'] = $bank['bank_acc_no'];
                $dataBank['bank_acc_name'] = $bank['bank_acc_name'];
                $dataBank['bank_city_name'] = $bank['bank_city_name'];
        }

        $view = new ViewModel();
        $view->setVariable('memberProfile', $profile);
        $view->setVariable('memberContact', $contact);
        $view->setVariable('bank', $dataBank);
        $this->layout('layout/admin');

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $memberId);

        return $view;
    }


    public function changepassAction() {
        $identity = $this->hasSession();
        // seting layout
        $this->layout('layout/admin');
        $view = new ViewModel();
        // init data and instance object

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $memberId = $identity->member_id;

        $request = $this->getRequest();
        if ($request->isPost()) {

            $conn->beginTransaction();

            $post = $request->getPost();

            $oldPass = $post->oldPass;
            $newPass = $post->newPass;

            $storage = new \MLM\Model\Member\Storage($db);
            $memberDetail = $storage->getMemberDetail($memberId);
            while ($memberDetail->next()) {
                $md = $memberDetail->current();
                $CurrPin = $md['pin'];
            }

            //Check Old Pass
            if ($CurrPin != md5($oldPass)){
                $view->setVariable('errmsg', 'Password Lama tidak sesuai');
                return $view;
            }


            $data = array(
                'pin'  => md5($newPass)
            );


            $where = array('member_id' => $memberId);

            $res = $storage->updateMember($data, $where);

            if(!$res){
                $conn->rollback();
                $view->setVariable('errmsg', 'Ganti Password Gagal');
                return $view;
            }


            $conn->commit();

            return $this->redirect()->toUrl('profile');

        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }



    public function resetpassAction() {
        $identity = $this->hasSession();
        // seting layout
        $this->layout('layout/admin');
        $view = new ViewModel();
        // init data and instance object

        $db = $this->_db;

        $conn = $db->getDriver()->getConnection();

        $request = $this->getRequest();
        if ($request->isPost()) {

            $conn->beginTransaction();

            $post = $request->getPost();

            $accNum = $post->accNum;
            $isAjax = $post->isAjax;

            $view->setVariable('isAjax', $isAjax);

            $storage = new \MLM\Model\Member\Storage($db);

            /*
             * GENERATE PASSWORD
             */

            $alpha = "abcdefghijklmnopqrstuvwxyz";
            $alpha_upper = strtoupper($alpha);
            $numeric = "0123456789";
            $length = 6;

            // default [a-zA-Z0-9]{9}
            $chars = $alpha . $alpha_upper . $numeric;

            $len = strlen($chars);
            $pw = '';

            for ($i=0;$i<$length;$i++){
                $pw .= substr($chars, rand(0, $len-1), 1);
            }

            $pw = str_shuffle($pw);

            /*
             *
             */


            $data = array(
                'pin'  => md5($pw)
            );


            $where = array('member_code' => $accNum);

            $res = $storage->updateMember($data, $where);

            if(!$res){
                $conn->rollback();
                $view->setVariable('errmsg', 'Reset Password Failed');
                return $view;
            }


            $conn->commit();

            $memberId = "";
            $memberName = "";
            $memberDet = $storage->getMemberDetailByCode($accNum);
            while ($memberDet->next()) {
                $md = $memberDet->current();
                $memberId = $md['member_id'];
                $memberName = $md['member_name'];
            }


            $accStorage = new \MLM\Model\Member\Contact\Storage($db);

            $memberMail = "";
            $memberContact = $accStorage->getMemberContact($memberId);
            while ($memberContact->next()) {
                $mc = $memberContact->current();
                $memberMail = $mc['contact_email'];
            }


            // Send notification email
            if ($memberMail != ""){
                $mailSubject = "Reset Password";
                $mailMsg = "<br><a href='fx-tradepoint.co.uk'>FX Trade Point</a><br><hr><br>
                            Dear ".$memberName.",<br>
                            Your Account Information with New Password:
                            <br><br><br>

                            Name : ".$memberName."<br><br>
                            Customer ID : ".$accNum."<br><br>
                            Password : ".$pw."<br><br>

                            <br><br>

                            Regards,<br>
                            FX Trade Point<br>
                            <hr><br><br>
                            <center>
                            For more information email us to info@fx-tradepoint.co.uk<br>
                            www.fx-tradepoint.co.uk
                            </center>";

                $functModel = new \MLM\Model\Functions;
                $functModel->sendMail($memberMail, $mailMsg, $mailSubject);
            }

            $view->setTerminal(true);

            $view->setVariable('msg', 'Reset Password Success');

        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        return $view;
    }

    
    public function membergrowthAction()
    {

        $identity = $this->hasSession();
        $this->layout('layout/admin');

        $date1 = date('Ymd', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $date2 = date('Ymd');

        $dateTmp1 = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d") - 7, date("Y")));
        $dateTmp2 = date('Y-m-d');

        $view = new ViewModel();

        $memberStorage = new \MLM\Model\Member\Storage($this->_db);
        $totalMember = $memberStorage->getNumMembers("");
        while ($totalMember->next()) {
                $res = $totalMember->current();
                
                $view->setVariable('totalMember', $res["total"]);
        }

        //Get Messages Notif
        $this->getMsgNotif($identity->member_type_id, $identity->member_id);

        $view->setVariable('dateTmp1', $dateTmp1);
        $view->setVariable('dateTmp2', $dateTmp2);
        
        $this->layout()->navMenu = "<li class='active'>Member</li> <li class='active'>Member Growth</li>";

        return $view;

    }
    
    //Get Messages Notif
    private function getMsgNotif($memberTypeId, $memberId){

        $notifStorage = new \MLM\Model\Notification\Storage($this->_db);
        $notifMsg = new \MLM\Model\Notification($notifStorage);
        $newMsgCnt = $notifMsg->getCountNewMsg($memberId);
        $newMsgList = $notifMsg->getNewMsgList($memberId);
        $newAlertCnt = $notifMsg->getCountAlertApproval($memberTypeId, $memberId);
        $newAlertList = $notifMsg->getAlertApproval($memberTypeId, $memberId);

        $action = $this->getEvent()->getRouteMatch()->getParam('action');
        $control = $this->getEvent()->getRouteMatch()->getParam('controller');

        $this->layout()->menu = $control.'\\'.$action;
        $this->layout()->newMsgCnt = $newMsgCnt;
        $this->layout()->newMsgList = $newMsgList;
        $this->layout()->newAlertCnt = $newAlertCnt;
        $this->layout()->newAlertList = $newAlertList;

    }

    public function loginAction() {
        $messages = '';
        $this->layout('layout/admin');
        $view = new ViewModel();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost();

            //$sm = $this->getServiceLocator();
            //$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');

         
            
            $authAdapter = new AuthAdapter($this->_db, 'members', // there is a method setTableName to do the same
                    'member_code', // there is a method setIdentityColumn to do the same
                    'pin', // there is a method setCredentialColumn to do the same
                    "MD5(?) AND member_type_id = 4 AND status_id = 1" // setCredentialTreatment(parametrized string) 'MD5(?)'
            );

            $authAdapter
                    ->setIdentity($post['username'])
                    ->setCredential($post['passwd'])
            ;

            $auth = new AuthenticationService();
            $result = $auth->authenticate($authAdapter);


            
            //print_r($result);
            switch ($result->getCode()) {
                case Result::FAILURE_IDENTITY_NOT_FOUND:
                    // do stuff for nonexistent identity
                    return $this->redirect()->toRoute('admin', array('controller' => 'Index', 'action' => 'login'));
                    //break;

                case Result::FAILURE_CREDENTIAL_INVALID:
                    // do stuff for invalid credential
                    return $this->redirect()->toRoute('admin', array('controller' => 'Index', 'action' => 'login'));
                    //break;

                case Result::SUCCESS:
                    $storage = $auth->getStorage();
                    $storage->write($authAdapter->getResultRowObject(
                                    null, 'pin'
                    ));
                    $time = 1209600; // 14 days 1209600/3600 = 336 hours => 336/24 = 14 days
//						if ($data['rememberme']) $storage->getSession()->getManager()->rememberMe($time); // no way to get the session

                    if ($post['rememberme']) {
                        $sessionManager = new \Zend\Session\SessionManager();
                        $sessionManager->rememberMe($time);
                    }
                    return $this->redirect()->toUrl('index');
                    //break;

                default:
                    // do stuff for other failure
                    break;
            }

            foreach ($result->getMessages() as $message) {
                $messages .= "$message\n";
            }

            $view->setVariable('msg', $messages);
            $view->setTemplate("mlm/member/blank.phtml");
            return $view;
        }

        
        $view->setTerminal(true);
        return $view;
        //echo "MSG = " . $messages;
        //$view->setVariable(array('msg' => $messages));
        
    }

    

    public function logoutAction() {
        $auth = new AuthenticationService();

        if ($auth->hasIdentity()) {
            $identity = $auth->getIdentity();
        }

        $auth->clearIdentity();
//		$auth->getStorage()->session->getManager()->forgetMe(); // no way to get the sessionmanager from storage
        $sessionManager = new \Zend\Session\SessionManager();
        $sessionManager->forgetMe();

        //return $this->redirect()->toRoute('admin', array('controller' => 'Index', 'action' => 'login'));
        return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
    }

    private function hasSession() {
        $auth = new AuthenticationService();

        $identity = $auth->getIdentity();

        if (!$auth->hasIdentity() || $identity->member_type_id <> 4) {
            //return $this->redirect()->toRoute('admin', array('controller' => 'Index', 'action' => 'login'));
            return $this->redirect()->toRoute('application/default', array('controller' => 'Index', 'action' => 'login'));
        } else {
            return $auth->getIdentity();
        }
    }

}
